//
//  TJGroupChatController.m
//  XWC
//
//  Created by Hello on 2022/10/24.
//

#import "HJGroupChatController.h"
#import "TUIDefine.h"
#import "HJChatGroupModel.h"
#import "HJIM.h"
#import "HJGroupSettingController.h"
#import "HJChatMessageModel.h"
#import "HJAlertController.h"
#import "HJGroupChatTopView.h"
#import "HJGroupNoticeController.h"
#import "HJGroupInviteController.h"
#import "HJGroupMemberModel.h"

@interface HJGroupChatController ()

@property (nonatomic, strong) HJChatGroupModel *groupModel;
@property (nonatomic, weak) HJGroupChatTopView *topView;
@property (nonatomic, strong) HJChatMessageModel *noticeModel;

@end

@implementation HJGroupChatController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.navigationBar.rightBarButton = [HJBarButton barButtonWithImage:[UIImage imageNamed:@"setting_icon"] target:self action:@selector(didClickGroupSettingButton)];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleRefreshGroupInfoNotification:) name:refreshGroupInfoNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleGroupSystemNotification:) name:groupSystemNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleSystemHandleCompleteNotification:) name:systemHandleCompleteNotification object:nil];
    
    HJGroupChatTopView *topView = [[HJGroupChatTopView alloc] initWithFrame:CGRectMake(0, KNavBarHight, KScreenWidth, 50)];
    [self.view addSubview:topView];
    topView.hidden = YES;
    _topView = topView;
    TJWeakify(self)
    [topView setDidClickItemBlock:^(HJCellModel * _Nonnull model) {
        if ([model.identifier isEqualToString:@"request"]){
            HJGroupInviteController *groupInviteController = [[HJGroupInviteController alloc] init];
            groupInviteController.groupId = weakself.groupModel.groupId;
            [weakself.navigationController pushViewController:groupInviteController];
            weakself.groupModel.hasApply = @2;
            [weakself.groupModel bg_saveOrUpdateAsync:^(BOOL isSuccess) {
                [weakself reloadTopViewWithType:HJGroupChatTopItemTypeRequest];
            }];
            return;
        }
        
        if ([model.identifier isEqualToString:@"notice"]){
            HJGroupNoticeController *groupNoticeController = [[HJGroupNoticeController alloc] init];
            groupNoticeController.groupModel = weakself.groupModel;
            [weakself.navigationController pushViewController:groupNoticeController];
            weakself.groupModel.showNotice = @0;
            [weakself.groupModel bg_saveOrUpdateAsync:^(BOOL isSuccess) {
                [weakself reloadTopViewWithType:HJGroupChatTopItemTypeNotice];
              
                weakself.noticeModel = nil;
                weakself.sessionModel.readMessageTimestamp = [NSString stringWithFormat:@"%.f", [NSDate date].timeIntervalSince1970 * 1000];
                weakself.sessionModel.unReadCount = @"0";
                weakself.sessionModel.hasNotice = @"0";
                [weakself.sessionModel bg_saveOrUpdate];
                HJChatSessionModel *sessionModel = [HJIM.shareIM.conversationManager getConversationBySessionId:weakself.sessionModel.sessionId];
                [[NSNotificationCenter defaultCenter] postNotificationName:updateConversationInfoNotification object:sessionModel];
            }];
            return;
        }
    }];
    
    [HJIM.shareIM.groupManager queryGroupInfoByGroupId:self.sessionModel.sessionId completion:^(HJChatGroupModel * _Nullable groupModel) {
        self.groupModel = groupModel;
        [self reloadTopViewWithType:HJGroupChatTopItemTypeAll];
        dispatch_async_main_queue(^{
            self.navigationBar.title = [NSString stringWithFormat:@"%@%@", self.sessionModel.sessionName, groupModel.memberNums.intValue > 0 ? [NSString stringWithFormat:@"(%@)", groupModel.memberNums] : @""];
        });
    }];
    
    [self loadGroupInfo];
    
}


- (void)showKickedAlert {
    [HJGroupMemberModel bg_deleteAsync:[HJGroupMemberModel bg_tableNameWithGroupId:self.groupModel.groupId] where:[NSString stringWithFormat:@"where %@=%@", bg_sqlKey(@"userId"), bg_sqlValue(HJUserInfo.userId)] complete:^(BOOL isSuccess) {}];
    dispatch_async_main_queue(^{
        [HJAlertController alertInController:self title:nil message:@"You have been removed from the group chat, and the chat messages will be cleared" left:nil right:^(HJAlertAction * _Nonnull action) {
            action.title = @"OK";
            action.titleColor = UIColor.tj_mainColor;
            [action setHandler:^{
                [HJIM.shareIM.conversationManager deleteConversationWithSessionId:self.groupModel.groupId completion:^(NSError * _Nonnull error) {
                    dispatch_async_main_queue(^{
                        [[NSNotificationCenter defaultCenter] postNotificationName:deleteConversationNotification object:self.groupModel.groupId];
                        [self.navigationController popToRootViewControllerAnimated:YES];
                    });
                }];
            }];
        }];
    });
}

- (void)showDisbandAlert {
    [HJGroupMemberModel bg_deleteAsync:[HJGroupMemberModel bg_tableNameWithGroupId:self.groupModel.groupId] where:[NSString stringWithFormat:@"where %@=%@", bg_sqlKey(@"userId"), bg_sqlValue(HJUserInfo.userId)] complete:^(BOOL isSuccess) {}];
    dispatch_async_main_queue(^{
        [HJAlertController alertInController:self title:nil message:@"This group has been disbanded, and relevant historical information will be cleared" left:nil right:^(HJAlertAction * _Nonnull action) {
            action.title = @"OK";
            action.titleColor = UIColor.tj_mainColor;
            [action setHandler:^{
                [HJIM.shareIM.conversationManager deleteConversationWithSessionId:self.groupModel.groupId completion:^(NSError * _Nonnull error) {
                    dispatch_async_main_queue(^{
                        [[NSNotificationCenter defaultCenter] postNotificationName:deleteConversationNotification object:self.groupModel.groupId];
                        [self.navigationController popToRootViewControllerAnimated:YES];
                    });
                }];
            }];
        }];
    });
}

- (void)didReceiveNewMessage:(HJChatMessageModel *)messageModel {
    [super didReceiveNewMessage:messageModel];
    
    if (messageModel.systemMsgType == HJChatSystemMsgTypePostGroupNotice || messageModel.messageType == HJMessageTypeNotice) {
        
        self.noticeModel = messageModel;
        
        [HJIM.shareIM.groupManager queryGroupInfoByGroupId:self.groupModel.groupId completion:^(HJChatGroupModel * _Nullable groupModel) {
            self.groupModel.notice = groupModel.notice;
            self.groupModel.showNotice = groupModel.showNotice;
            [self reloadTopViewWithType:HJGroupChatTopItemTypeNotice];

        }];
        return;
    } else if (messageModel.systemMsgType == HJChatSystemMsgTypeModifyGroupName && messageModel.groupName) {
        self.groupModel.name = messageModel.groupName;
        self.navigationBar.title = [NSString stringWithFormat:@"%@%@", messageModel.groupName, self.groupModel.memberNums.intValue > 0 ? [NSString stringWithFormat:@"(%@)", self.groupModel.memberNums] : @""];
    }

}

- (void)handleSystemHandleCompleteNotification:(NSNotification *)not {
    
    HJChatMessageModel *messageModel = not.object;
    
    if (![messageModel.groupId isEqualToString:self.groupModel.groupId]) return;
    
    if (messageModel.systemMsgType == HJChatSystemMsgTypeJoinGroup ||
        messageModel.systemMsgType == HJChatSystemMsgTypeLeaveGroup) {
        [self loadGroupInfo];
        return;
    }
    
    if (messageModel.systemMsgType == HJChatSystemMsgTypeJoinGroup){
        [self loadGroupInfo];
        if (self.groupModel.role.intValue == 1 || self.groupModel.role.intValue == 2) {//群主和管理员在有成员加入的时候, 是否显示有新的申请
            [HJIM.shareIM.groupManager loadGroupInviteCountWithGroupId:self.groupModel.groupId complete:^(NSInteger count) {
                dispatch_async_sql_queue(^{
                    if (count == 0) {
                        self.groupModel.hasApply = @0;
                        [self.groupModel bg_saveOrUpdate];
                        [self reloadTopViewWithType:HJGroupChatTopItemTypeRequest];
                    }
                });
            }];
        }
        return;
    }
    
    
}

- (void)handleGroupSystemNotification:(NSNotification *)not {
    HJChatMessageModel *messageModel = not.object;
    
    if (![messageModel.groupId isEqualToString:self.groupModel.groupId]) return;
    
    if (messageModel.systemMsgType == HJChatSystemMsgTypeDisbandGroup) {
        if ([messageModel.senderId isEqualToString:HJUserInfo.userId]) return;
        self.groupModel.groupStatus = 1;
        [self.groupModel bg_saveOrUpdateAsync:nil];
        [self showDisbandAlert];
        return;
    }
    
    if (messageModel.systemMsgType == HJChatSystemMsgTypeKickOutGroup) {
        if ([messageModel.senderId isEqualToString:HJUserInfo.userId]) return;
        self.groupModel.groupStatus = 2;
        [self.groupModel bg_saveOrUpdateAsync:nil];
        [self showKickedAlert];
        return;
    }
    
    if (messageModel.systemMsgType == HJChatSystemMsgTypeApplyJoinGroup) {
        [HJIM.shareIM.groupManager loadGroupInviteCountWithGroupId:self.groupModel.groupId complete:^(NSInteger count) {
            dispatch_async_sql_queue(^{
                HJChatGroupModel *groupModel = [HJIM.shareIM.groupManager queryGroupInfoByGroupId:self.groupModel.groupId];
                self.groupModel.extension = groupModel.extension;
                [self.groupModel bg_saveOrUpdate];
                self.groupModel.hasApply = count > 0 ? @1 : @0;
                [self reloadTopViewWithType:HJGroupChatTopItemTypeRequest];
            });
        }];
        return;
    }
}

- (void)handleRefreshGroupInfoNotification:(NSNotification *)not {
    
    id object = not.object;
    if ([object isKindOfClass:NSString.class]) {
        NSString *sessionId = object;
        if ([sessionId isEqualToString:self.sessionModel.sessionId]) {
            [self loadGroupInfo];
        }
    } else if ([object isKindOfClass:HJChatGroupModel.class]) {
        HJChatGroupModel *groupModel = (HJChatGroupModel *)object;
        if ([groupModel.groupId isEqualToString:self.sessionModel.sessionId]) {
            self.navigationBar.title = [NSString stringWithFormat:@"%@%@", groupModel.name, self.groupModel.memberNums.intValue > 0 ? [NSString stringWithFormat:@"(%@)", self.groupModel.memberNums] : @""];
            [self updateSessionNameWithGroupModel:groupModel];
        }
    }
}

- (void)didClickGroupSettingButton {
    if (!_groupModel) {
        _groupModel = [[HJChatGroupModel alloc] init];
        _groupModel.groupId = self.sessionModel.sessionId;
        _groupModel.name = self.sessionModel.sessionName;
        _groupModel.avatar = self.sessionModel.sessionAvatar;
    }
    HJGroupSettingController *groupSettingController = [[HJGroupSettingController alloc] init];
    groupSettingController.groupModel = self.groupModel;
    [self.navigationController pushViewController:groupSettingController];
}

- (void)reloadTopViewWithType:(HJGroupChatTopItemType)type {
    
    NSMutableArray *topDatas = [NSMutableArray array];

    dispatch_async_main_queue(^{
        
        if (self.groupModel.hasApply.intValue == 1 && (self.groupModel.role.intValue == 1 || self.groupModel.role.intValue == 2)) {
            [topDatas addObject:[HJCellModel modelWithBlock:^(HJCellModel * _Nonnull model) {
                model.iconName = @"createGroup";
                model.text = @"Join Requests";
                model.identifier = @"request";
                model.anyObject = @(HJGroupChatTopItemTypeRequest);
            }]];
        }
        
        if (self.groupModel.showNotice.intValue == 1 || TJIM_isSelf(self.noticeModel.senderId)) {
            [topDatas addObject:[HJCellModel modelWithBlock:^(HJCellModel * _Nonnull model) {
                model.iconName = @"top_notice_icon";
                model.text = self.groupModel.notice;
                model.identifier = @"notice";
                model.anyObject = @(HJGroupChatTopItemTypeNotice);
            }]];
        }
        
        if (topDatas.count) {
            if (topDatas.count == 2) {
                HJCellModel *topModel = nil;
                for (HJCellModel *model in topDatas) {
                    if ([model.anyObject integerValue] == type) {
                        topModel = model;
                        break;
                    }
                }
                
                if (topModel) {
                    [topDatas removeObject:topModel];
                    [topDatas insertObject:topModel atIndex:0];
                }
            }
            
            self.topView.hidden = NO;
            self.messageController.topMargin = self.topView.tj_height;
            self.topView.datas = topDatas;
        } else {
            self.topView.datas = topDatas;
            self.messageController.topMargin = 0;
            self.topView.hidden = YES;
        }
    });
    
}

- (void)loadGroupInfo {
    
    [HJIM.shareIM.groupManager loadGroupInfoByGroupId:self.sessionModel.sessionId completion:^(HJChatGroupModel * _Nullable groupModel) {
        if (!groupModel) return;
        
        BOOL hasApply = groupModel.hasApply.intValue == 1;
        BOOL showNotice = groupModel.showNotice.intValue == 1 || TJIM_isSelf(self.noticeModel.senderId);
        
        BOOL lastHasApply = self.groupModel.hasApply.intValue == 1;
        BOOL lastShowNotice = self.groupModel.showNotice.intValue == 1 || TJIM_isSelf(self.noticeModel.senderId);
        
        if (!(lastHasApply == hasApply && showNotice == lastShowNotice)) {
            [self reloadTopViewWithType:HJGroupChatTopItemTypeAll];
        }
        
        groupModel.extension = self.groupModel.extension;
        self.groupModel = groupModel;
        self.navigationBar.title = [NSString stringWithFormat:@"%@%@", self.groupModel.name, self.groupModel.memberNums.intValue > 0 ? [NSString stringWithFormat:@"(%@)", self.groupModel.memberNums] : @""];
                
        if (self.groupModel.showNotice.intValue != 1) {
            HJChatSessionModel *sessionModel = [HJIM.shareIM.conversationManager getConversationBySessionId:self.sessionModel.sessionId];
            //会话列表显示群公告的的时候才刷新
            if ((sessionModel.hasNotice.boolValue && (sessionModel.timestamp.integerValue > sessionModel.readMessageTimestamp.integerValue))) {
                sessionModel.hasNotice = @"0";
                sessionModel.readMessageTimestamp = [NSString stringWithFormat:@"%.f", [NSDate date].timeIntervalSince1970 * 1000];
                [sessionModel bg_saveOrUpdateAsync:^(BOOL isSuccess) {}];
                [[NSNotificationCenter defaultCenter] postNotificationName:updateConversationInfoNotification object:sessionModel];
            }
        }
        
        if (self.groupModel.groupStatus == 1 || self.groupModel.status.intValue == 2) {
            [self showDisbandAlert];
        } else if (self.groupModel.userStatus == 2) {
            [self showKickedAlert];
        }
        
        [self updateSessionNameWithGroupModel:groupModel];
    }];
}

- (void)updateSessionNameWithGroupModel:(HJChatGroupModel *)groupModel {
    BOOL isUpdate = !(groupModel.avatar && [groupModel.avatar isEqualToString:self.sessionModel.sessionAvatar] && [groupModel.name isEqualToString:self.sessionModel.sessionName]);
    if (isUpdate) {
        [HJIM.shareIM.conversationManager getConversationBySessionId:self.sessionModel.sessionId completion:^(HJChatSessionModel * _Nonnull sessionModel) {
            sessionModel.sessionAvatar = groupModel.avatar;
            sessionModel.sessionName = groupModel.name;
            [sessionModel bg_saveOrUpdate];
            [[NSNotificationCenter defaultCenter] postNotificationName:updateConversationInfoNotification object:sessionModel];
        }];
    }
}
 
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    [self loadGroupInfo];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    TJLog(@"%s", __func__);
}


@end
